<template>
  <el-form :ref="refName" :model="formData" :inline="isInline" size="mini" :disabled="disabled">
    <el-row>
      <el-col :span="24 / colNumOfRow"
        v-for="(field, index) in formFields"
        :key="index">
        <el-form-item
          :prop="field.prop"
          :label="field.label"
          :label-width="field.width || formItemWidth"
          :required="field.required"
          :rules="[{ required: field.required, message: `${field.label}不能为空`, trigger: ['change', 'blur']}]"
        >
          <!-- 普通下拉框 -->
          <template v-if="field.type === 'select'">
            <el-select
              v-model="formData[field.prop]"
              style="width: 100%"
              :multiple="field.multiple"
              :filterable="field.filterable"
              :filter-method="field.filterMethod"
              :placeholder="field.placeholder || `请选择${field.label}`"
              :disabled="field.disabled"
              :clearable="field.clearable"
              :collapse-tags="field.collapseTags === false ? false : true"
              @input="(data)=>{handleFieldChanged(data, field)}"
            >
              <el-option
                v-for="item in field.options"
                :key="item.value || item.sysTypeId || item.id || item.manageAreaId"
                :label="item.label || item.sysTypeName || item.itemValue || item.manageAreaName"
                :value="item.value || item.sysTypeId || item.id || item.manageAreaId"
                :disabled="item.disabled"
              />
            </el-select>
            <span
              v-if="!field.multiple ? oldValue[field.prop]&&(formData[field.prop] != oldValue[field.prop]) : oldValue[field.prop]&&(JSON.parse(oldValue[field.prop]).toString() != formData[field.prop].toString())"
              class="diff-span"
            >原字段参数：{{ !field.multiple ? list2Obj(field.options)[oldValue[field.prop]] : formatSelectOldVal(field.options, oldValue[field.prop], field.prop)}}</span>
          </template>
          <!-- 日期范围选择 -->
          <template v-else-if="field.type === 'dateRange'">
            <el-date-picker
              style="width: 100%"
              v-model="formData[field.prop]"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :placeholder="field.placeholder || `请选择${field.label}`">
            </el-date-picker>
            <span
              v-if="oldValue[field.prop]&&(formData[field.prop] != oldValue[field.prop])"
              class="diff-span"
            >原字段参数：{{oldValue[field.prop]}}</span>
          </template>
          <!-- 日期选择 -->
          <template v-else-if="field.type === 'date'">
            <el-date-picker
              style="width: 100%"
              v-model="formData[field.prop]"
              value-format="yyyy-MM-dd"
              type="date"
              :placeholder="field.placeholder || `请选择${field.label}`">
            </el-date-picker>
            <span
              v-if="oldValue[field.prop]&&(formData[field.prop] != oldValue[field.prop])"
              class="diff-span"
            >原字段参数：{{oldValue[field.prop]}}</span>
          </template>
          <!-- 日期时间选择 -->
          <template v-else-if="field.type === 'dateTime'">
            <el-date-picker
              v-model="formData[field.prop]"
              :type="field.datePickerType || 'datetime'"
              style="width: 100%"
              :value-format="field.valueFormat || 'yyyy-MM-dd HH:mm:ss'"
              :range-separator="field.rangeSeparator || '-'"
              :start-placeholder="field.startPlaceholder || '开始日期'"
              :end-placeholder="field.endPlaceholder || '结束日期'"
              :disabled="field.disabled"
              :default-time="field.defaultTime"
              :placeholder="field.placeholder || `请选择${field.label}`"
              :picker-options="field.pickerOptions"
            />
            <span
              v-if="oldValue[field.prop]&&(formData[field.prop] != oldValue[field.prop])"
              class="diff-span"
            >原字段参数：{{oldValue[field.prop]}}</span>
          </template>
          <!-- 日期时间范围选择 -->
          <template v-else-if="field.type === 'dateTimeRange'">
            <el-date-picker
              v-model="formData[field.prop]"
              :type="field.datePickerType || 'datetimerange'"
              style="width: 100%"
              :value-format="field.valueFormat || 'yyyy-MM-dd HH:mm:ss'"
              :range-separator="field.rangeSeparator || '-'"
              :start-placeholder="field.startPlaceholder || '开始日期'"
              :end-placeholder="field.endPlaceholder || '结束日期'"
              :disabled="field.disabled"
              :default-time="field.defaultTime"
              :placeholder="field.placeholder || `请选择${field.label}`"
            />
            <span
              v-if="oldValue[field.prop]&&(formData[field.prop] != oldValue[field.prop])"
              class="diff-span"
            >原字段参数：{{oldValue[field.prop]}}</span>
          </template>
          <!-- 数字输入框 -->
          <template v-else-if="field.type === 'inputNum'">
            <el-input-number
              v-model.trim="formData[field.prop]"
              style="width: 100%"
              :placeholder="field.placeholder || `请输入${field.label}`"
              :disabled="field.disabled"
              controls-position="right"
              :min="field.min"
              :max="field.max"
              :precision="field.precision"
              @change="(data)=>{handleFieldChanged(data, field)}"
            />
            <span
              v-if="oldValue[field.prop]&&(formData[field.prop] != oldValue[field.prop])"
              class="diff-span"
            >原字段参数：{{oldValue[field.prop]}}</span>
          </template>
          <!-- 自定义数字输入框 -->
          <template v-else-if="field.type === 'inputNumSpecial'">
            <InputNumber
              v-model.trim="formData[field.prop]"
              style="width: 100%"
              :placeholder="field.placeholder || `请输入${field.label}`"
              :disabled="field.disabled"
              :controls="false"
              controls-position="right"
              :min="field.min"
              :max="field.max"
              :precision="field.precision"
              @change="(data)=>{handleFieldChanged(data, field)}"
            />
            <span
              v-if="oldValue[field.prop]&&(formData[field.prop] != oldValue[field.prop])"
              class="diff-span"
            >原字段参数：{{oldValue[field.prop]}}</span>
          </template>
          <!-- 文本输入框 -->
          <template v-else-if="field.type === 'inputText'">
            <el-input
              type="textarea"
              v-model.trim="formData[field.prop]"
              :placeholder="field.placeholder || `请输入${field.label}`"
              :disabled="field.disabled"
              :maxlength="field.maxlength"
              :show-word-limit="!!field.maxlength"
              :rows="1"
            />
            <span
              v-if="oldValue[field.prop]&&(formData[field.prop] != oldValue[field.prop])"
              class="diff-span"
            >原字段参数：{{oldValue[field.prop]}}</span>
          </template>
          <template v-else-if="field.type === 'annex'">
            <span v-if="formData[field.prop]">
              <AnnexDownloadButton
                v-model.trim="formData[field.prop]"
                :fileName="field.fileName || field.label" />
              <el-tooltip effect="dark" content="删除" v-if="!field.disabled && !disabled">
                <i class="delete-icon el-icon-close" @click="handleDelteAnnex(field.prop)"></i>
              </el-tooltip>
            </span>
            <AnnexUploadButton v-else
              v-model="formData[field.prop]"
              :typeList="field.typeList"
              @onUploaded="(params)=>{handleUploaded(params, field)}" />
          </template>
          <!-- 管理区域 -->
          <template v-else-if="field.type === 'managementArea'">
            <ManagementAreaSelect ref="managementArea" v-model="formData[field.prop]" />
          </template>
          <!-- 主营品类 -->
          <template v-else-if="field.type === 'categorySelect'">
            <CategorySelect
              setName
              ref="categorySelect"
              v-model="formData[field.prop]"
              @onSelected="(param)=>{handleCategorySelect(param, field)}"
            />
            <span
              v-if="oldValue[field.prop]&&(formData[field.prop] != oldValue[field.prop])"
              class="diff-span"
            >原字段参数：{{oldValue[field.prop]}}</span>
          </template>
          <!-- 地址选择 -->
          <template v-else-if="field.type === 'addressSelect'">
            <AddressSelect :ref="field.ref || 'addressSelect'" v-model="formData[field.prop]" />
          </template>
          <!-- 文本按钮 -->
          <template v-else-if="field.type === 'button'">
            <el-row type="flex">
              <el-button
                v-for="item in field.buttonList"
                :key="item.key"
                :type="item.type || 'text'"
                @click="handleClickButton(item, field)"
              >{{ item.label }}</el-button>
            </el-row>
          </template>
          <!-- 普通输入框 -->
          <template v-else>
            <el-input
              v-model.trim="formData[field.prop]"
              :placeholder="field.placeholder || `请输入${field.label}`"
              :disabled="field.disabled"
              :maxlength="field.maxlength"
              :show-word-limit="!!field.maxlength"
            />
            <span
              v-if="oldValue[field.prop]&&(formData[field.prop] != oldValue[field.prop])"
              class="diff-span"
            >原字段参数：{{oldValue[field.prop]}}</span>
          </template>
        </el-form-item>
      </el-col>
    </el-row>
    <BusinessCategoryDialog
      :visible.sync="businessCategory.visible"
      :categoryUuids="Array.isArray(formData.supplierManageCategoryList) ? formData.supplierManageCategoryList.map(item => item.categoryUuid) : []"
      @getCheckedCategory="getCheckedCategory"
    />
    <basic-dialog
      title="已选经营品类"
      :visible.sync="viewDialog.visible"
      :showFooter="false"
      :handleClose="handleColseDialog"
    >
      <ShowCategoryTags
        class="show_category_tags_wrap"
        :dataSource="formData.supplierManageCategoryList"
      />
    </basic-dialog>
  </el-form>
</template>

<script>
import ManagementAreaSelect from '@/components/supplier/ManagementAreaSelect'
import CategorySelect from '@/pages/supplier/components/SelectMainCategory'
import AddressSelect from '@/components/supplier/AddressSelect'
import BasicDialog from '@/components/BasicDialog';
import BusinessCategoryDialog from '@/components/supplier/BusinessCategoryDialog';
import ShowCategoryTags from '@/components/supplier/BusinessCategoryDialog/ShowCategoryTags';
import { list2Obj } from '@/pages/supplier/utils';
import AnnexUploadButton from '@/pages/supplier/components/annexUploadButton' // 上传附件按钮
import AnnexDownloadButton from '@/pages/supplier/components/annexDownloadButton' // 下载附件按钮
import InputNumber from '@/components/inputNumber/inputNumber'

export default {
  components: {
    ManagementAreaSelect,
    CategorySelect,
    AddressSelect,
    BusinessCategoryDialog,
    BasicDialog,
    ShowCategoryTags,
    AnnexUploadButton,
    AnnexDownloadButton,
    InputNumber
  },
  props: {
    refName: { // 表单ref名
      type: String,
      default: 'reportInfoForm'
    },
    formData: { // 表单formData
      type: Object,
      default () {
        return {};
      }
    },
    oldValue: { // 表单formData原值
      type: Object,
      default () {
        return {};
      }
    },
    isInline: { // 表单是否开启inline模式
      type: Boolean,
      default: false
    },
    disabled: { // 表单是否开启禁用
      type: Boolean,
      default: false
    },
    colNumOfRow: { // 表单每行col数量
      type: Number,
      default: 3
    },
    formItemWidth: { // 表单item默认宽度
      type: String,
      default: '150px'
    },
    formFields: { // 表单项集合
      type: Array,
      default () {
        return [];
      }
    },
  },
  data () {
    return {
      form: {},
      businessCategory: {
        visible: false
      },
      viewDialog: {
        visible: false,
        list: []
      }
    };
  },
  watch: {
    formData: {
      handler (newVal) {
        this.form = newVal
      },
      immediate: true,
      deep: true
    }
  },
  mounted () {
    this.$emit('update:formData', this.form)
  },
  methods: {
    list2Obj,
    handleCategorySelect (data, field) {
      if (field.prop === 'mainCategory' && this.formData.hasOwnProperty('mainCategoryCode')) {
        this.formData.mainCategory = data.categoryName
        this.formData.mainCategoryCode = data.categoryNo
        this.formData.mainCategoryId = data.uuid
      }
    },
    handleClickButton (item, field) {
      const methodByType = {
        'view': () => this.handleViewCategoryInfo(field),
        'edit': this.handleEditCategoryInfo
      }
      const runMethod = methodByType[item.key] || (() => {});
      runMethod();
    },
    handleViewCategoryInfo (field) {
      this.viewDialog.visible = true;
      this.viewDialog.list = this.formData[field.prop] || [];
    },
    handleEditCategoryInfo () {
      this.businessCategory.visible = true;
    },
    getCheckedCategory ({ source }) {
      this.formData.supplierManageCategoryList = source;
    },
    handleColseDialog () {
      this.viewDialog.visible = false;
    },
    // 格式
    formatSelectOldVal (options, oldVal, prop) {
      if (prop == 'etcQaExecuteArea') {
        return options.filter(ele => JSON.parse(oldVal).includes(ele.manageAreaId)).map((i) => i.manageAreaName)
      }
      if (prop == 'packingRequire') {
        return options.filter(ele => JSON.parse(oldVal).includes(ele.id)).map((i) => i.itemValue)
      }
    },
    handleFieldChanged (value, field) {
      const { prop } = field
      if (prop == 'rebate') {
        if (value == 31) {
          this.$refs[this.refName].resetFields()
          this.formData.rebate = 31
        }
      }
      // 结账时间
      if (prop == 'checkoutTime') {
        if (value != 40289) {
          this.formData.paidType = ''
          this.formData.checkoutRange = ''
        }
      }
      // 结账区间
      if (prop == 'checkoutRange') {
        // 40287 结账前 40288 结账后
        if (value != 1101) {
          this.formData.taxBillProvideTime = 40287
        } else {
          this.formData.taxBillProvideTime = 40288
        }
      }
      // 是否集中结账 30 是 31 否
      if (prop == 'centralizedSettle') {
        // 否时清空集中结账地
        if (value == 31) {
          this.formData.centralizedSettlePlace = null
        }
      }
      // 结算方式 承兑时，承兑比例默认为100%，不可编辑，承兑金额非必填
      if (prop == 'settlementType') {
        const acceptList = [40, 40290, 40293] // 银行承兑 商业承兑 银行承兑+商业承兑
        if (acceptList.includes(value)) {
          this.formData.acceptRatio = '100'
        }
      }
      // 铺底质保金
      if (prop == 'initialCapital') {
        if (value == 0) {
          this.formData.initialCapitalCollectType = '';
        }
      }
      // 质量保证金
      if (prop == 'retentionMoney') {
        if (value == 0) {
          this.formData.retentionMoneyCollectType = '';
        }
      }
      // 纳税人类型
      if (prop == 'generalTaxpayer') {
        this.formData.invoiceType = 102
        if (value == 30) {
          this.formData.taxBillRate1 = 39879
        } else if (value == 31) {
          this.formData.taxBillRate1 = 39875
        }
      }
      // 后续待办
      // 1:'潜在转合格 2:'合格转潜在' 3:'潜在转线索' 4:'供应商淘汰' 5:'供应商拉黑'
      // 6:'修改资质' 7:'修改登记表信息' 8: 签订合同 9:增加供货信息 10:价格调整
      if (prop == 'subsequentBacklog') {
        field.options.map(item => {
          item.disabled = (value.includes('1') && !['1', '7', '8'].includes(item.value)) ||
          (value.includes('2') && !['2', '7', '8'].includes(item.value)) ||
          (value.includes('3') && !['3'].includes(item.value)) ||
          (value.includes('4') && !['4'].includes(item.value)) ||
          (value.includes('5') && !['5'].includes(item.value)) ||
          (value.includes('6') && !['6', '9', '10'].includes(item.value)) ||
          (value.includes('7') && !['7', '1', '2', '9', '10'].includes(item.value)) ||
          (value.includes('8') && !['8', '1', '2', '9', '10'].includes(item.value)) ||
          (value.includes('9') && ['9', '2', '3'].includes(item.value)) ||
          (value.includes('10') && ['10', '2', '3'].includes(item.value))
        })
      }
    },
    // 上传关系证明
    handleUploaded ({ response, file }, field) {
      const { prop } = field;
      this.formData[prop] = response?.result || ''
    },
    // 删除附件
    handleDelteAnnex (prop) {
      this.formData[prop] = ''
    },
  }
}
</script>
<style  lang="less" scoped>
.diff-span {
  font-size: 12px;
  color: #F56C6C;
  margin-top: -5px;
  display: block;
  height: 5px;
}
/deep/.el-form-item__label {
  font-size: 12px!important
}
</style>
